<template>
  <div class="protection-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="query-panel" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>查询条件</span>
            </div>
          </template>
          <el-form :model="queryForm" label-width="80px">
            <el-form-item label="防护类型">
              <el-checkbox-group v-model="queryForm.protectionTypes">
                <el-checkbox label="aircraft">飞机防护</el-checkbox>
                <el-checkbox label="oil">油料防护</el-checkbox>
                <el-checkbox label="ammunition">弹药防护</el-checkbox>
                <el-checkbox label="parking">停机坪防护</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery" :loading="loading" class="w-100">查询</el-button>
            </el-form-item>
          </el-form>
          
          <!-- 错误信息显示 -->
          <div v-if="error" class="error-message">
            <el-alert
              :title="error"
              type="error"
              show-icon
              :closable="true"
              @close="error = ''"
            />
          </div>
        </el-card>
        
        <!-- 防护设施说明 -->
        <el-card class="legend-panel" shadow="hover" v-if="queryForm.protectionTypes.includes('aircraft')">
          <template #header>
            <div class="card-header">
              <span>飞机防护设施说明</span>
            </div>
          </template>
          <div class="legend-content">
            <div v-for="(item, index) in aircraftLegend" :key="index" class="legend-item">
              <div class="legend-color" :style="{ 'background-color': item.color }"></div>
              <div class="legend-name">{{ item.name }}</div>
              <div class="legend-desc">{{ item.desc }}</div>
            </div>
          </div>
        </el-card>
        
        <el-card class="legend-panel" shadow="hover" v-if="queryForm.protectionTypes.includes('oil')">
          <template #header>
            <div class="card-header">
              <span>油料防护设施说明</span>
            </div>
          </template>
          <div class="legend-content">
            <div v-for="(item, index) in oilLegend" :key="index" class="legend-item">
              <div class="legend-color" :style="{ 'background-color': item.color }"></div>
              <div class="legend-name">{{ item.name }}</div>
              <div class="legend-desc">{{ item.desc }}</div>
            </div>
          </div>
        </el-card>
        
        <el-card class="legend-panel" shadow="hover" v-if="queryForm.protectionTypes.includes('ammunition')">
          <template #header>
            <div class="card-header">
              <span>弹药防护设施说明</span>
            </div>
          </template>
          <div class="legend-content">
            <div v-for="(item, index) in ammoLegend" :key="index" class="legend-item">
              <div class="legend-color" :style="{ 'background-color': item.color }"></div>
              <div class="legend-name">{{ item.name }}</div>
              <div class="legend-desc">{{ item.desc }}</div>
            </div>
          </div>
        </el-card>
        
        <el-card class="legend-panel" shadow="hover" v-if="queryForm.protectionTypes.includes('parking')">
          <template #header>
            <div class="card-header">
              <span>停机坪防护设施说明</span>
            </div>
          </template>
          <div class="legend-content">
            <div v-for="(item, index) in parkingLegend" :key="index" class="legend-item">
              <div class="legend-color" :style="{ 'background-color': item.color }"></div>
              <div class="legend-name">{{ item.name }}</div>
              <div class="legend-desc">{{ item.desc }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="18">
        <el-card class="map-container" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>{{ statsTitle }}</span>
              
              <!-- 添加统计切换按钮 -->
              <div class="view-toggle">
                <el-radio-group v-model="viewMode" size="small">
                  <el-radio-button label="facility">设施分布</el-radio-button>
                  <el-radio-button label="stats">区域统计</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          
          <!-- 加载指示器 -->
          <div v-if="loading" class="loading-overlay">
            <div class="spinner"></div>
          </div>
          
          <!-- 地图视图 -->
          <div class="map-view">
            <div id="taiwanMap" ref="mapContainer" class="map"></div>
            
            <!-- 区域统计面板 -->
            <div v-if="viewMode === 'stats'" class="stats-panel">
              <div class="stats-header">{{ statsTitle }}</div>
              <div class="stats-content">
                <div v-for="(stat, index) in regionStats" :key="index" class="stat-item">
                  <div class="stat-name">{{ stat.name }}</div>
                  
                  <div class="stat-bar-container">
                    <div 
                      class="stat-bar" 
                      :style="{ 
                        width: stat.percentage + '%', 
                        backgroundColor: getRegionColor(index)
                      }"
                    ></div>
                    <span class="stat-value">{{ stat.totalValue.toFixed(0) }} m² ({{ stat.percentage.toFixed(1) }}%)</span>
                  </div>
                  
                  <!-- 各类型占比详情 -->
                  <div class="protection-type-bars" v-if="stat.facilities">
                    <div v-for="(type, typeName) in stat.facilities" :key="typeName" class="type-bar-item">
                      <div class="type-bar-container">
                        <div 
                          class="type-bar" 
                          :style="{ 
                            width: stat.totalValue ? (type.value / stat.totalValue * 100) + '%' : '0%',
                            backgroundColor: getProtectionTypeColor(typeName) 
                          }"
                        ></div>
                      </div>
                      <span class="type-label">{{ getTypeLabel(typeName) }} ({{ type.count }}个)</span>
                    </div>
                  </div>
                </div>
              </div>
              
              <div class="stats-legend">
                <div class="legend-title">防护设施类型</div>
                <div class="types-legend">
                  <div v-for="(type, index) in queryForm.protectionTypes" :key="type" class="type-legend-item">
                    <div class="type-color" :style="{ backgroundColor: getProtectionTypeColor(type) }"></div>
                    <div class="type-label">{{ getTypeLabel(type) }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'
import { getProtectionData } from '@/api/protection'
import * as echarts from 'echarts/core'
import { PieChart } from 'echarts/charts'
import { CanvasRenderer } from 'echarts/renderers'
import { TitleComponent, TooltipComponent, LegendComponent } from 'echarts/components'

// 注册必要的ECharts组件
echarts.use([
  PieChart,
  CanvasRenderer,
  TitleComponent,
  TooltipComponent,
  LegendComponent
])

export default {
  name: 'ProtectionView',
  setup() {
const queryForm = ref({
      protectionTypes: ['aircraft', 'oil', 'ammunition', 'parking'] // 默认选中所有防护类型
    })

    const loading = ref(false)
    const error = ref('')
    const viewMode = ref('facility')
    const mapContainer = ref(null) // 添加地图容器引用
    
    // 地图实例
    let mapInstance = null
    let markersLayer = null
    
    // 各类防护设施数据
    const protectionData = ref({
      aircraft: { categories: [], regions: [] },
      oil: { categories: [], regions: [] },
      ammunition: { categories: [], regions: [] },
      parking: { categories: [], regions: [] }
    })
    
    // 各防护设施类型对应的颜色
    const typeColors = {
      aircraft: '#5470c6',
      oil: '#91cc75',
      ammunition: '#fac858',
      parking: '#ee6666'
    }
    
    // 区域统计数据
    const regionStats = computed(() => {
      const stats = {}
      const result = []
      
      // 处理所有选中类型的数据
      queryForm.value.protectionTypes.forEach(type => {
        if (protectionData.value[type] && protectionData.value[type].regions) {
          protectionData.value[type].regions.forEach(region => {
            if (!stats[region.name]) {
              stats[region.name] = {
                name: region.name,
                facilities: {}
              }
            }
            
            stats[region.name].facilities[type] = {
              count: region.airports.length,
              value: region.airports.reduce((sum, airport) => {
                if (airport.values && Array.isArray(airport.values)) {
                  return sum + airport.values.reduce((s, v) => s + v, 0)
                }
                return sum
              }, 0)
            }
          })
        }
      })
      
      // 计算总面积和百分比
      let totalArea = 0
      Object.values(stats).forEach(region => {
        region.totalValue = Object.values(region.facilities).reduce((sum, f) => sum + f.value, 0)
        totalArea += region.totalValue
      })
      
      // 转换为数组并计算百分比
      Object.values(stats).forEach(region => {
        region.percentage = totalArea > 0 ? (region.totalValue / totalArea) * 100 : 0
        result.push(region)
      })
      
      return result.sort((a, b) => b.totalValue - a.totalValue) // 按总价值降序排列
    })
    
    // 统计标题
    const statsTitle = computed(() => {
      if (queryForm.value.protectionTypes.length === 0) {
        return '防护设施统计'
      } else if (queryForm.value.protectionTypes.length === 1) {
        return `${getTypeLabel(queryForm.value.protectionTypes[0])}统计`
      } else {
        return '多类型防护设施统计'
      }
    })
    
    // 获取区域颜色
    const getRegionColor = (index) => {
      const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272']
      return colors[index % colors.length]
    }
    
    // 获取防护类型颜色
    const getProtectionTypeColor = (type) => {
      return typeColors[type] || '#999'
    }
    
    // 获取防护类型标签
    const getTypeLabel = (type) => {
      const typeMap = {
        'aircraft': '飞机防护',
        'oil': '油料防护',
        'ammunition': '弹药防护',
        'parking': '停机坪防护'
      }
      return typeMap[type] || type
    }
    
    // 飞机防护设施图例
    const aircraftLegend = [
      { name: '洞库', color: '#5470c6', desc: '提供飞机最高等级的防护' },
      { name: '掩蔽库', color: '#91cc75', desc: '提供一定程度的防护' },
      { name: '机库', color: '#fac858', desc: '普通室内存放环境' },
      { name: '机棚', color: '#ee6666', desc: '基本防晒雨设施' },
      { name: '飞机掩体', color: '#73c0de', desc: '抗炸弹的飞机单体掩体' }
    ]
    
    // 油料防护设施图例
    const oilLegend = [
      { name: '地下油罐', color: '#5470c6', desc: '地下油料设施，提供最高等级的防护' },
      { name: '半地下油罐', color: '#91cc75', desc: '半地下油料设施，提供中等程度的防护' },
      { name: '地面油罐', color: '#fac858', desc: '地面油料设施，易受攻击' }
    ]
    
    // 弹药防护设施图例
    const ammoLegend = [
      { name: '地下弹药库', color: '#5470c6', desc: '地下弹药设施，提供最高等级的防护' },
      { name: '半地下弹药库', color: '#91cc75', desc: '半地下弹药设施，提供中等程度的防护' },
      { name: '地面弹药库', color: '#fac858', desc: '地面弹药设施，易受攻击' }
    ]
    
    // 停机坪防护设施图例
    const parkingLegend = [
      { name: '个体停机坪', color: '#5470c6', desc: '带护坡的个体停机坪' },
      { name: '群体停机坪', color: '#91cc75', desc: '多机共用的停机坪' },
      { name: '分散停机坪', color: '#fac858', desc: '分散式布局的停机坪' }
    ]
    
    // 获取图表标题
    const getChartTitle = () => {
      switch(queryForm.value.protectionType) {
        case 'aircraft':
          return '飞机防护能力分析 (按面积)'
        case 'oil':
          return '油料防护能力分析 (按面积)'
        case 'ammunition':
          return '弹药防护能力分析 (按面积)'
        default:
          return '防护能力分析'
      }
    }
    
    // 窗口调整处理
    const handleWindowResize = () => {
      if (mapInstance) {
        mapInstance.invalidateSize()
      }
    }
    
    // 初始化Leaflet地图
    const initMap = () => {
      // 创建备用图层
      const createFallbackLayer = () => {
        console.log('创建备用图层...')
        
        // 清除现有图层
        if (mapInstance) {
          mapInstance.eachLayer(layer => {
            if (layer instanceof L.TileLayer) {
              mapInstance.removeLayer(layer)
            }
          })
        }
        
        // 创建简单的背景图层
        const fallbackLayer = L.rectangle(
          [[21.5, 119.5], [25.4, 122.5]],
          { 
            color: '#e0e0e0', 
            weight: 1, 
            fillColor: '#f8f8f8', 
            fillOpacity: 1
          }
        ).addTo(mapInstance)
        
        // 添加台湾轮廓
        const taiwanOutline = [
          [25.3, 121.5], // 台北
          [24.8, 120.9], // 新竹
          [24.1, 120.7], // 台中
          [23.5, 120.5], // 嘉义
          [23.0, 120.2], // 台南
          [22.6, 120.3], // 高雄
          [22.0, 120.7], // 屏东
          [22.8, 121.2], // 台东
          [23.6, 121.5], // 花莲
          [24.5, 121.8], // 宜兰
          [25.3, 121.5]  // 回到台北
        ]
        
        L.polyline(taiwanOutline, {
          color: '#666',
          weight: 2
        }).addTo(mapInstance)
        
        // 添加主要城市标记
        const cities = [
          { name: '台北', pos: [25.0, 121.5] },
          { name: '台中', pos: [24.1, 120.7] },
          { name: '高雄', pos: [22.6, 120.3] }
        ]
        
        cities.forEach(city => {
          L.circleMarker(city.pos, {
            radius: 4,
            color: '#333',
            fillColor: '#999',
            fillOpacity: 1
          }).bindTooltip(city.name).addTo(mapInstance)
        })
      }

      // 如果地图已经初始化，先销毁它
      if (mapInstance) {
        mapInstance.remove()
        mapInstance = null
      }

      const mapContainer = document.getElementById('taiwanMap')
      if (!mapContainer) {
        console.error('Map container not found')
        return
      }

      // 确保容器可见并有明确的尺寸
      mapContainer.style.width = '100%'
      mapContainer.style.height = '600px'

      // 创建地图实例
      mapInstance = L.map('taiwanMap', {
        center: [23.7, 121.0],  // 台湾中心位置
        zoom: 8,                // 固定初始缩放级别为8，匹配我们的瓦片
        zoomControl: true,
        scaleControl: true,
        minZoom: 8,
        maxZoom: 13,
        zoomSnap: 1,
        zoomDelta: 1,
        wheelPxPerZoomLevel: 120,
        maxBounds: L.latLngBounds(
          L.latLng(21.5, 119.5),  // 西南角
          L.latLng(25.4, 122.5)   // 东北角
        ),
        maxBoundsViscosity: 1.0
      })
      
      // 创建并添加离线地图图层
      try {
        console.log('正在加载离线地图...')
        
        // 创建自定义图层类
        const CustomTileLayer = L.TileLayer.extend({
          // 重写检查瓦片是否应该加载的方法
          _isValidTile: function(coords) {
            // 只允许特定范围的瓦片
            if (coords.z === 8) {
              // 缩放级别为8时，只允许x=213-214, y=109-112的瓦片
              return (coords.x === 213 || coords.x === 214) && 
                     (coords.y >= 109 && coords.y <= 112);
            }
            
            // 默认返回原始检查结果
            return true;
          },
          
          getTileUrl: function(coords) {
            // 限制只请求我们已知存在的瓦片范围
            const z = coords.z;
            const x = coords.x;
            const y = coords.y;
            
            // 对于缩放级别8，我们只有x=213-214, y=109-112的瓦片
            if (z === 8) {
              if (x !== 213 && x !== 214) {
                return ''; // 返回空字符串，不加载不存在的瓦片
              }
              
              if (y < 109 || y > 112) {
                return ''; // 返回空字符串，不加载不存在的瓦片
              }
            }
            
            return `/assets/map-of-taiwan/gaode_map/${z}/${x}/${y}.png`;
          }
        });
        
        // 创建瓦片图层
        const offlineLayer = new CustomTileLayer('', {
          minZoom: 8,
          maxZoom: 13,
          tileSize: 256,
          attribution: '高德地图离线数据',
          errorTileUrl: '',
          noWrap: true,
          bounds: L.latLngBounds(
            L.latLng(21.5, 119.5),  // 西南角
            L.latLng(25.4, 122.5)   // 东北角
          )
        });
        
        // 添加错误处理
        offlineLayer.on('tileerror', function(error) {
          console.error('瓦片加载错误:', {
            url: error.tile.src,
            status: error.tile.errorEvent
          })
          
          // 隐藏错误的瓦片
          if (error.tile && error.tile.style) {
            error.tile.style.display = 'none'
          }
          
          // 记录错误次数
          if (!window.tileErrorCount) {
            window.tileErrorCount = 0
          }
          window.tileErrorCount++
          
          // 如果错误太多，创建备用图层
          if (window.tileErrorCount > 10 && !window.fallbackCreated) {
            console.log('瓦片错误过多，创建备用图层')
            window.fallbackCreated = true
            createFallbackLayer()
          }
        })
        
        // 添加加载成功处理
        offlineLayer.on('load', function() {
          
        })
        
        // 使用离线地图数据
        offlineLayer.addTo(mapInstance)
        
        // 在地图加载后强制重新计算大小
        setTimeout(() => {
          if (mapInstance) {
            console.log('强制刷新地图大小')
            mapInstance.invalidateSize()
          }
        }, 500)
      } catch(e) {
        console.error("加载地图图层失败:", e)
        error.value = `加载地图失败: ${e.message}`
        createFallbackLayer()
      }
      
      // 创建标记图层
      markersLayer = L.layerGroup().addTo(mapInstance)
      
      return mapInstance
    }
    
    // 获取防护数据
    const fetchProtectionData = async () => {
      loading.value = true
      error.value = ''
      
      // 如果没有选择任何防护类型，显示警告并返回
      if (queryForm.value.protectionTypes.length === 0) {
        ElMessage.warning('请选择至少一种防护类型')
        loading.value = false
        return
      }
      
      try {
        console.log('开始获取防护设施数据，选择的类型：', queryForm.value.protectionTypes)
        
        // 使用Promise.all请求多个数据
        const promises = queryForm.value.protectionTypes.map(type => {
          console.log(`请求${type}类型的数据`)
          return getProtectionData(type)
            .then(res => ({ type, data: res }))
            .catch(err => {
              console.error(`获取${type}类型数据失败:`, err)
              return { type, error: err, data: null }
            })
        })
        
        const results = await Promise.all(promises)
        
        // 处理结果
        results.forEach(result => {
          const { type, data, error: dataError } = result
          
          if (data) {
            console.log(`成功获取${type}类型数据:`, data)
            protectionData.value[type] = data
          } else {
            console.warn(`未能获取${type}类型数据，使用模拟数据`)
            // 这里不再使用模拟数据，而是提示用户
            ElMessage.warning(`无法获取${getTypeLabel(type)}数据，请检查后端服务`)
          }
        })
        
        // 更新地图数据
        updateMap()
      } catch (err) {
        console.error('获取防护设施数据失败:', err)
        error.value = '获取数据失败，请稍后重试'
      } finally {
        loading.value = false
      }
    }
    
    // 创建饼图标记
    const createPieChartMarker = (latlng, data, types) => {
      // 创建一个DOM元素来容纳饼图
      const chartContainer = L.DomUtil.create('div', 'pie-chart-marker')
      chartContainer.style.width = '40px'
      chartContainer.style.height = '40px'
      
      // 创建自定义图标
      const icon = L.divIcon({
        className: 'pie-chart-icon',
        html: chartContainer,
        iconSize: [40, 40],
        iconAnchor: [20, 20]
      })
      
      // 创建标记
      const marker = L.marker(latlng, { icon }).addTo(markersLayer)
      
      // 生成饼图数据
      const pieData = []
      types.forEach(type => {
        if (data[type] && data[type].value > 0) {
          pieData.push({
            name: getTypeLabel(type),
            value: data[type].value,
            itemStyle: { color: typeColors[type] }
          })
        }
      })
      
      // 确保至少有数据再创建图表
      if (pieData.length > 0) {
        // 使用nextTick确保DOM已经渲染
        nextTick(() => {
          // 初始化ECharts实例
          const chart = echarts.init(chartContainer)
          
          // 配置选项
          const option = {
            series: [{
              type: 'pie',
              radius: ['5%', '90%'],
              center: ['50%', '50%'],
              data: pieData,
              label: { show: false },
              emphasis: { scale: false },
              animation: false
            }]
          }
          
          // 设置图表选项
          chart.setOption(option)
        })
      }
      
      // 设置标记的弹出框内容
      let popupContent = `<div class="popup-content"><div class="popup-title">${data.name}</div>`
      
      // 添加各类型详情
      types.forEach(type => {
        if (data[type] && data[type].count > 0) {
          popupContent += `<div class="popup-type">${getTypeLabel(type)}</div><div class="popup-stats">`
          
          if (type === 'aircraft') {
            popupContent += `
              <div class="stat-item"><span>洞库:</span> ${data.aircraftDetails?.caveCapacity || 0}m²</div>
              <div class="stat-item"><span>掩蔽库:</span> ${data.aircraftDetails?.shelterCapacity || 0}m²</div>
              <div class="stat-item"><span>机库:</span> ${data.aircraftDetails?.hangarCapacity || 0}m²</div>
              <div class="stat-item"><span>部署飞机:</span> ${data.aircraftDetails?.aircraftCount || 0}</div>
            `
          } else if (type === 'oil') {
            popupContent += `
              <div class="stat-item"><span>地下油罐:</span> ${data.oilDetails?.underground || 0}m²</div>
              <div class="stat-item"><span>半地下油罐:</span> ${data.oilDetails?.semiUnderground || 0}m²</div>
              <div class="stat-item"><span>地面油罐:</span> ${data.oilDetails?.ground || 0}m²</div>
              <div class="stat-item"><span>油罐数量:</span> ${data.oilDetails?.count || 0}个</div>
            `
          } else if (type === 'ammunition') {
            popupContent += `
              <div class="stat-item"><span>地下弹药库:</span> ${data.ammoDetails?.underground || 0}m²</div>
              <div class="stat-item"><span>半地下弹药库:</span> ${data.ammoDetails?.semiUnderground || 0}m²</div>
              <div class="stat-item"><span>地面弹药库:</span> ${data.ammoDetails?.ground || 0}m²</div>
              <div class="stat-item"><span>弹药库数量:</span> ${data.ammoDetails?.count || 0}个</div>
            `
          } else if (type === 'parking') {
            popupContent += `
              <div class="stat-item"><span>个体停机坪:</span> ${data.parkingDetails?.individual || 0}m²</div>
              <div class="stat-item"><span>群体停机坪:</span> ${data.parkingDetails?.group || 0}m²</div>
              <div class="stat-item"><span>分散停机坪:</span> ${data.parkingDetails?.dispersed || 0}m²</div>
              <div class="stat-item"><span>停机坪数量:</span> ${data.parkingDetails?.count || 0}个</div>
            `
          }
          
          popupContent += `</div>`
        }
      })
      
      popupContent += `</div>`
      marker.bindPopup(popupContent)
      
      return marker
    }
    
    // 更新地图标记
    const updateMap = () => {
      if (!mapInstance || !markersLayer) return
      
      // 清除旧的标记图层
      if (markersLayer) {
        markersLayer.clearLayers()
  } else {
        markersLayer = L.layerGroup().addTo(mapInstance)
      }
      
      // 如果是统计视图，不添加标记
      if (viewMode.value === 'stats') {
        calculateRegionStats()
        return
      }
      
      // 合并相同位置的数据
      const airportData = {}
      
      // 遍历选中的防护类型，收集数据
      queryForm.value.protectionTypes.forEach(type => {
        const data = protectionData.value[type]
        if (!data || !data.regions) return
        
        // 遍历区域数据
        data.regions.forEach(region => {
          if (!region.airports) return
          
          // 遍历机场数据
          region.airports.forEach(airport => {
            // 跳过无经纬度的数据
            if (!airport.latitude || !airport.longitude) return
            
            const key = `${airport.latitude},${airport.longitude}`
            
            // 如果这个位置还没有数据，初始化
            if (!airportData[key]) {
              airportData[key] = {
                name: airport.name,
                latitude: airport.latitude,
                longitude: airport.longitude,
                region: region.name
              }
            }
            
            // 添加该类型的数据
            const totalValue = Array.isArray(airport.values) 
              ? airport.values.reduce((sum, val) => sum + val, 0)
              : 0
            
            airportData[key][type] = {
              value: totalValue,
              count: 0
            }
            
            // 根据不同类型添加详细信息
            if (type === 'aircraft') {
              airportData[key].aircraftDetails = {
                caveCapacity: airport.values[0] || 0,
                shelterCapacity: airport.values[1] || 0,
                hangarCapacity: airport.values[2] || 0,
                aircraftCount: airport.aircraft || 0
              }
              airportData[key][type].count = 5 // 假设有5种设施
            } else if (type === 'oil') {
              airportData[key].oilDetails = {
                underground: airport.values[0] || 0,
                semiUnderground: airport.values[1] || 0,
                ground: airport.values[2] || 0,
                count: airport.tanks?.length || 0
              }
              airportData[key][type].count = airport.tanks?.length || 0
            } else if (type === 'ammunition') {
              airportData[key].ammoDetails = {
                underground: airport.values[0] || 0,
                semiUnderground: airport.values[1] || 0,
                ground: airport.values[2] || 0,
                count: airport.depots?.length || 0
              }
              airportData[key][type].count = airport.depots?.length || 0
            } else if (type === 'parking') {
              airportData[key].parkingDetails = {
                individual: airport.values[0] || 0,
                group: airport.values[1] || 0,
                dispersed: airport.values[2] || 0,
                count: airport.aprons?.length || 0
              }
              airportData[key][type].count = airport.aprons?.length || 0
            }
          })
        })
      })
      
      // 创建饼图标记
      Object.keys(airportData).forEach(key => {
        const data = airportData[key]
        const latlng = [data.latitude, data.longitude]
        createPieChartMarker(latlng, data, queryForm.value.protectionTypes)
      })
    }
    
    // 计算区域统计数据
    const calculateRegionStats = () => {
      const stats = {}
      let totalValue = 0
      
      // 遍历选中的防护类型
      queryForm.value.protectionTypes.forEach(type => {
        const data = protectionData.value[type]
        if (!data || !data.regions) return
        
        // 遍历区域
        data.regions.forEach(region => {
          if (!region.airports) return
          
          const regionName = region.name
          
          // 初始化区域数据
          if (!stats[regionName]) {
            stats[regionName] = {
              name: regionName,
              totalValue: 0,
              percentage: 0,
              facilities: {}
            }
          }
          
          // 遍历机场
          region.airports.forEach(airport => {
            // 获取该防护类型的总值
            let airportTotal = 0
            if (airport.values && airport.values.length) {
              airportTotal = airport.values.reduce((sum, val) => sum + val, 0)
            }
            
            // 更新区域总值
            stats[regionName].totalValue += airportTotal
            totalValue += airportTotal
            
            // 初始化该区域中的设施类型计数
            if (!stats[regionName].facilities[type]) {
              stats[regionName].facilities[type] = { value: 0, count: 0 }
            }
            
            // 统计各类型设施
            stats[regionName].facilities[type].value += airportTotal
            
            // 根据不同的防护类型计算设施数量
            if (type === 'aircraft') {
              stats[regionName].facilities[type].count += 5 // 假设5种防护设施都有
            } else if (type === 'oil' && airport.tanks) {
              stats[regionName].facilities[type].count += airport.tanks.length
            } else if (type === 'ammunition' && airport.depots) {
              stats[regionName].facilities[type].count += airport.depots.length
            } else if (type === 'parking' && airport.aprons) {
              stats[regionName].facilities[type].count += airport.aprons.length
            }
          })
        })
      })
      
      // 计算百分比
      Object.keys(stats).forEach(regionName => {
        if (totalValue > 0) {
          stats[regionName].percentage = (stats[regionName].totalValue / totalValue) * 100
        }
      })
      
      // 将对象转换为数组并按照值排序
      const result = Object.values(stats).sort((a, b) => b.totalValue - a.totalValue)
      
      // 更新统计数据
      regionStats.value = result
    }
    
    // 生命周期钩子
    onMounted(() => {
      // 初始化Leaflet地图
      nextTick(() => {
        // 确保DOM已完全加载
        setTimeout(() => {
          const mapContainer = document.getElementById('taiwanMap')
          if (mapContainer) {
            mapContainer.style.height = '600px'
            mapContainer.style.width = '100%'
          }
          
          initMap()
          // 获取初始数据
          fetchProtectionData()
        }, 100)
      })
      
      // 添加窗口调整监听
      window.addEventListener('resize', handleWindowResize)
    })
    
    onUnmounted(() => {
      // 移除窗口调整监听
      window.removeEventListener('resize', handleWindowResize)
      
      // 销毁地图实例
      if (mapInstance) {
        mapInstance.remove()
        mapInstance = null
      }
    })
    
    // 监听防护类型变化
    watch(() => queryForm.value.protectionTypes, (newValue, oldValue) => {
      if (JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
        fetchProtectionData()
      }
    }, { deep: true })
    
    const handleSwitchView = (mode) => {
      viewMode.value = mode
      nextTick(() => {
        if (mode === 'facility' && mapInstance) {
          // 刷新地图上的标记
          updateMap()
        }
      })
    }
    
    // 添加处理查询的函数
    const handleQuery = () => {
      fetchProtectionData()
    }

    return {
      queryForm,
      loading,
      error,
      viewMode,
      mapContainer,
      regionStats,
      statsTitle,
      typeColors,
      aircraftLegend,
      oilLegend,
      ammoLegend,
      parkingLegend,
      getRegionColor,
      getProtectionTypeColor,
      getTypeLabel,
      handleQuery,
      handleSwitchView
    }
  }
}
</script>

<style scoped>
.protection-container {
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.filter-section {
  margin-bottom: 10px;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.map-container {
  position: relative;
  flex: 1;
  overflow: hidden;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.map-view {
  position: relative;
  width: 100%;
  height: 600px; /* 设置一个明确的高度 */
  background-color: #f0f0f0;
  border: 1px solid #ddd;
}

#taiwanMap {
  width: 100% !important;
  height: 100% !important;
  z-index: 10;
  position: relative;
  min-height: 600px;
}

/* 自定义弹窗样式 */
:deep(.custom-popup) {
  min-width: 250px;
  max-width: 300px;
}

:deep(.custom-popup h3) {
  margin: 0 0 5px 0;
  color: #409EFF;
  font-size: 16px;
}

:deep(.custom-popup h4) {
  margin: 10px 0 5px 0;
  font-size: 14px;
}

:deep(.custom-popup p) {
  margin: 5px 0;
  font-size: 13px;
}

:deep(.custom-tooltip) {
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  border: none;
  padding: 3px 8px;
  border-radius: 3px;
  font-size: 12px;
}

/* 表格样式美化 */
:deep(.popup-table) {
  width: 100%;
  border-collapse: collapse;
  font-size: 12px;
}

:deep(.popup-table td) {
  padding: 3px 5px;
}

/* 饼图标记样式 */
:deep(.pie-chart-marker) {
  width: 40px !important;
  height: 40px !important;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.8);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  pointer-events: auto; /* 允许与图表交互 */
}

:deep(.pie-chart-icon) {
  display: block !important;
  margin: 0 !important;
  padding: 0 !important;
  border: none !important;
  background: none !important;
}

:deep(.leaflet-popup-content-wrapper) {
  border-radius: 8px;
  min-width: 200px;
}

:deep(.popup-content) {
  padding: 5px;
}

:deep(.popup-title) {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 5px;
}

:deep(.popup-type) {
  font-weight: bold;
  margin: 8px 0 4px;
  color: #409EFF;
}

:deep(.popup-stats) {
  margin-bottom: 8px;
}

:deep(.stat-item) {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
  color: #666;
  margin-bottom: 4px;
}

:deep(.stat-item span) {
  font-weight: 500;
  color: #333;
}

/* 条形图样式 */
:deep(.facility-bars) {
  margin: 5px 0;
}

:deep(.facility-bar-item) {
  margin-bottom: 4px;
}

:deep(.facility-bar-label) {
  font-size: 12px;
  margin-bottom: 2px;
}

:deep(.facility-bar-container) {
  width: 100%;
  height: 6px;
  background-color: #f0f0f0;
  border-radius: 3px;
  overflow: hidden;
}

:deep(.facility-bar) {
  height: 100%;
  border-radius: 3px;
}

/* 图例样式 */
.legend-panel {
  margin-top: 20px;
}

.legend-content {
  padding: 10px 0;
}

.legend-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.legend-color {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  margin-right: 10px;
}

.legend-name {
  font-weight: bold;
  margin-right: 10px;
  min-width: 80px;
}

.legend-desc {
  font-size: 12px;
  color: #666;
  flex: 1;
}

.w-100 {
  width: 100%;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .protection-container {
    padding: 10px;
  }
  
  .legend-name {
    min-width: 60px;
  }
}

@media (max-width: 768px) {
  .protection-container {
    padding: 5px;
  }
  
  #taiwanMap {
    height: 400px;
  }
  
  .legend-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .legend-color {
    margin-bottom: 5px;
  }
}

.stats-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 320px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.15);
  padding: 15px;
  z-index: 1000;
}

.stats-header {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  text-align: center;
}

.stats-content {
  margin-bottom: 15px;
}

.stat-item {
  margin-bottom: 10px;
}

.stat-name {
  font-size: 14px;
  margin-bottom: 4px;
}

.stat-bar-container {
  height: 18px;
  background-color: #f0f0f0;
  border-radius: 9px;
  overflow: hidden;
  position: relative;
}

.stat-bar {
  height: 100%;
  border-radius: 9px;
}

.stat-value {
  position: absolute;
  right: 10px;
  top: 0;
  height: 18px;
  line-height: 18px;
  font-size: 12px;
  color: #333;
}

.stats-legend {
  border-top: 1px solid #eee;
  padding-top: 10px;
}

.legend-title {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 8px;
}

.legend-items {
  display: flex;
  flex-wrap: wrap;
}

.legend-item {
  display: flex;
  align-items: center;
  margin-right: 12px;
  margin-bottom: 5px;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 3px;
  margin-right: 5px;
}

.legend-label {
  font-size: 12px;
  color: #555;
}

.view-toggle {
  margin-left: 20px;
}

/* 视图切换按钮样式 */
.view-switcher {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 4px;
  padding: 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.view-btn {
  padding: 8px 15px;
  border: none;
  background: transparent;
  cursor: pointer;
  border-radius: 3px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.view-btn.active {
  background: #409eff;
  color: white;
}

.view-btn:not(:last-child) {
  margin-right: 8px;
}

/* 统计面板样式 */
.stats-panel {
  position: absolute;
  top: 80px;
  right: 20px;
  width: 320px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  max-height: 70vh;
  overflow-y: auto;
}

.stats-header {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  text-align: center;
  color: #333;
}

.stats-content {
  margin-bottom: 20px;
}

.stat-item {
  margin-bottom: 12px;
}

.stat-label {
  font-weight: 500;
  margin-bottom: 4px;
}

.stat-bar-container {
  height: 12px;
  background: #f0f0f0;
  border-radius: 6px;
  overflow: hidden;
}

.stat-bar {
  height: 100%;
  border-radius: 6px;
}

.stat-value {
  font-size: 13px;
  color: #666;
  text-align: right;
  margin-top: 2px;
}

/* 图例样式 */
.stats-legend {
  border-top: 1px solid #eee;
  padding-top: 15px;
}

.legend-title {
  font-weight: 500;
  margin-bottom: 10px;
}

.legend-item {
  display: flex;
  margin-bottom: 8px;
  align-items: center;
}

.legend-color {
  width: 14px;
  height: 14px;
  border-radius: 3px;
  margin-right: 8px;
}

.legend-info {
  flex: 1;
}

.legend-name {
  font-weight: 500;
  font-size: 14px;
}

.legend-desc {
  font-size: 12px;
  color: #666;
}
</style> 